package com.mydemo.likedy.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mydemo.likedy.Constant.RedisConstant;
import com.mydemo.likedy.Service.UserRegisterService;
import com.mydemo.likedy.Utils.RedisCacheUtil;
import com.mydemo.likedy.exception.BaseException;
import com.mydemo.likedy.mapper.UserMapper;
import com.mydemo.likedy.pojo.dto.RegisterDTO;
import com.mydemo.likedy.pojo.entity.Favorites;
import com.mydemo.likedy.pojo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserRegisterServiceImpl extends ServiceImpl<UserMapper, User> implements UserRegisterService {
    @Autowired
    RedisCacheUtil redisCacheUtil;

    @Override
    public boolean register(RegisterDTO registerDTO) {
        // 邮箱是否存在
        final int count = (int) this.count(new LambdaQueryWrapper<User>().eq(User::getEmail, registerDTO.getEmail()));
        if (count == 1) {
            throw new BaseException("邮箱已被注册");
        }
        final String code = registerDTO.getCode();
        final Object o = redisCacheUtil.get(RedisConstant.EMAIL_CODE + registerDTO.getEmail());
        if (o == null) {
            throw new BaseException("验证码为空");
        }
        if (!code.equals(o)) {
            return false;
        }
        //创建新用户,对密码进行加密
        final User user = new User();
        user.setNickName(registerDTO.getNickName());
        user.setEmail(registerDTO.getEmail());
        user.setDescription("这个人很懒...");
        user.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()));
        save(user);

        // 创建默认收藏夹
        final Favorites favorites = new Favorites();
        favorites.setUserId((long)user.getId());
        favorites.setName("默认收藏夹");

//        // 这里如果单独抽出一个用户配置表就好了,但是没有必要再搞个表
//        user.setDefaultFavoritesId(favorites.getId());
//        updateById(user);
        return true;
    }
}
